package yf.mall.controller.api.cp;

import com.yf.annotation.IgnoreAuth;
import com.yf.annotation.LoginUserId;
import com.yf.response.R;
import com.yf.response.RRException;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.bean.WxJsapiSignature;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.WxCpAgentJsapiSignature;
import me.chanjar.weixin.cp.bean.kf.WxCpKfCustomerBatchGetResp;
import org.springframework.web.bind.annotation.*;
import yf.mall.utils.StringUtil;
import yf.mall.config.cp.WxCpConfiguration;
import yf.mall.config.cp.WxCpProperties;
import yf.mall.entity.UserEntity;
import yf.mall.enums.LevelEnum;
import yf.mall.service.UserService;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping("/api/wx/cp")
@Slf4j
public class WxCpController {

    @PostMapping("/user/update")
    @IgnoreAuth
    public R kfUpdateUser(Long id, String dyNumber, String remark) {
        UserEntity user = userService.get(id);
        user.setRemark(remark);
        user.setDyNumber(dyNumber);
        userService.update(user);
        return R.ok();
    }

    @GetMapping("/js/config/{corpId}/{agentId}")
    @IgnoreAuth
    public R jsConfig(@PathVariable Integer agentId, @PathVariable String corpId, String uri) {
        final WxCpService wxCpService = WxCpConfiguration.getCpService(agentId);
        if (wxCpService == null) {
            throw new IllegalArgumentException(String.format("未找到对应agentId=[%d]的配置，请核实！", agentId));
        }

        WxJsapiSignature wxJsapiSignature;
        try {
            wxJsapiSignature = wxCpService.createJsapiSignature(uri);
        } catch (WxErrorException e) {
            log.error("获取企业微信签名失败", e);
            throw new RRException("获取企业微信签名失败");
        }
        String signature = wxJsapiSignature.getSignature();
        String nonceStr = wxJsapiSignature.getNonceStr();
        long timestamp = wxJsapiSignature.getTimestamp();
        Map res = new HashMap<String, String>();
        res.put("appId", corpId); // 必填，企业微信的corpID
        res.put("timestamp", timestamp); // 必填，生成签名的时间戳
        res.put("nonceStr", nonceStr); // 必填，生成签名的随机串
        res.put("signature", signature); // 必填，签名，见 附录-JS-SDK使用权限签名算法
        return R.ok(res);
    }

    @GetMapping("/agent/config/{corpId}/{agentId}")
    @IgnoreAuth
    public R agentConfig(@PathVariable Integer agentId, @PathVariable String corpId, String uri) {
        final WxCpService wxCpService = WxCpConfiguration.getCpService(agentId);
        if (wxCpService == null) {
            throw new IllegalArgumentException(String.format("未找到对应agentId=[%d]的配置，请核实！", agentId));
        }

        WxCpAgentJsapiSignature agentJsapiSignature;
        try {
            agentJsapiSignature = wxCpService.createAgentJsapiSignature(uri);
        } catch (WxErrorException e) {
            log.error("获取企业微信签名失败", e);
            throw new RRException("获取企业微信签名失败");
        }
        String signature = agentJsapiSignature.getSignature();
        String nonceStr = agentJsapiSignature.getNonceStr();
        long timestamp = agentJsapiSignature.getTimestamp();
        Map res = new HashMap<String, String>();
        res.put("appId", corpId); // 必填，企业微信的corpID
        res.put("timestamp", timestamp); // 必填，生成签名的时间戳
        res.put("nonceStr", nonceStr); // 必填，生成签名的随机串
        res.put("signature", signature); // 必填，签名，见 附录-JS-SDK使用权限签名算法
        return R.ok(res);
    }

    @Resource
    private UserService userService;

    /**
     * 这里是调用微信客服的secret
     * https://developer.work.weixin.qq.com/document/path/95159
     *
     * @param userId
     * @param agentId
     * @return
     */
    @GetMapping("/user/{agentId}")
    @IgnoreAuth
    public R userInfo(String userId, @PathVariable Integer agentId) {
        final WxCpService wxCpService = WxCpConfiguration.getCpService(agentId);
        try {
            WxCpKfCustomerBatchGetResp info = wxCpService.getKfService().customerBatchGet(Arrays.asList(userId));
            String unionId = info.getCustomerList().get(0).getUnionId();
            if (StringUtil.isBlank(unionId)) {
                throw new RRException("unionId不存在");
            }
            UserEntity user = userService.findByWxId(unionId);
            if (user == null) {
                log.error("企业微信用户不存在:{}",unionId);
                throw new RRException("用户不存在!");
            }
            UserEntity chatUser = userService.getChatUserInfo(user.getId());
            return R.ok(chatUser);
        } catch (WxErrorException e) {
            log.error("企业微信获取用户信息失败", e);
            throw new RRException("获取用户信息失败");
        }
    }

    @Resource
    private WxCpProperties wxCpProperties;

    /**
     * 获取企业微信客服客服
     * 统计五个组
     * 客服一个组 服务商 连营才有
     *
     * @return
     */
    @GetMapping("/chat/url")
    public R chatUrl(@LoginUserId  Long userId) {


        //用户信息
        UserEntity  user =  userService.getChatUserInfo(userId);

        //服务号 和 联营
        Boolean cpChat = LevelEnum.levelOf(user.getLevelId()).lv <= LevelEnum.FW.lv;

        if (!Optional.ofNullable(wxCpProperties.getChat()).orElse(false)||!cpChat) {
            return R.ok(user).putExtra("cpChat",false);
        }

        if(cpChat&&StringUtil.isBlank(user.getUnionId())){
            throw new RRException("未绑定微信");
        }

        String chatUrl = wxCpProperties.getChatUrl();
        String lyChatUrl = null;
//        chat = false; //这里暂时改成 没有匹配就没有开启
        if(user.getLevelId().equals(LevelEnum.LY.levelId)&&user.getRemark()!=null){
            String[] names = new String[]{"联营一组","联营二组","联营三组","联营四组","联营五组"};
            for (int i = 0; i < names.length; i++) {
                String name = names[i];
                if(user.getRemark().contains(name)){
//                    chat = true;
                    lyChatUrl = wxCpProperties.getLyChatUrls().get(i);
                    break;
                }
            }
            //没有匹配 默认一组
            if(lyChatUrl==null){
                lyChatUrl = wxCpProperties.getLyChatUrls().get(0);
            }
        }
        return R.ok(user).putExtra("cpChat",true).putExtra("chatUrl",chatUrl).putExtra("lyChatUrl",lyChatUrl);
    }

}
